import { useEffect } from "react";
import { Table, Space, Divider, Card, Badge, Popconfirm } from "antd";
import { Button, Card as SemiCard, Row, Col, List, ButtonGroup } from "@douyinfe/semi-ui";
import { IconRefresh } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";

import { AllApplications, AllApplicationTypesByAiUuid, UpdateApplication } from "../_graphql/applications";
import { message } from "antd";

const { Column } = Table;

const LocalApplications = () => {
    const { windowInnerHeight, graphqlFetch, UTCTimeToLocal } = useModel("global");
    const { organizationUuid } = useModel("organization.info");

    const state = useReactive({
        loading: false,
        infoLoading: false,
        localApplications: [],
        selectedApplication: {},
        members: [],
        clients: [],
    });

    const loadLocalApplications = async () => {
        state.loading = true;
        let local = await graphqlFetch({ query: AllApplications, variables: {} });
        state.localApplications = local?.a?.nodes || [];
        let selectedApplication = state.localApplications.find((item) => item.aiUuid === state.selectedApplication?.aiUuid);
        !selectedApplication && state.localApplications.length > 0 && (selectedApplication = state.localApplications[0]);
        state.selectedApplication = selectedApplication;
        state.loading = false;
    };

    useEffect(() => {
        if (organizationUuid) {
            loadLocalApplications();
        }
    }, [organizationUuid]);

    const loadClients = async () => {
        state.infoLoading = true;
        let res = await graphqlFetch({
            query: AllApplicationTypesByAiUuid,
            variables: { aiUuid: state.selectedApplication.aiUuid },
        });
        state.clients = res?.a?.nodes || [];
        state.infoLoading = false;
    };

    const loadApplicationMembers = async () => {
        state.infoLoading = true;
        let query = `query MyQuery($aiUuid: UUID!) {
            a: applicationByAiUuid(aiUuid: $aiUuid) {
              b: applicationRoleByAiAona {
                c: applicationRolesMembersByArUuid {
                  totalCount
                  nodes {
                    member: organizationMemberByOmUuid {
                      omUuid
                      omName
                      omIfim
                    }
                  }
                }
              }
            }
        }`;
        let res = await graphqlFetch({
            query,
            variables: {
                aiUuid: state.selectedApplication.aiUuid,
            },
        });
        state.members = res?.a?.b?.c?.nodes.map((item) => item.member);
        state.infoLoading = false;
    };

    useEffect(() => {
        if (state.selectedApplication?.aiUuid) {
            loadClients();
            state.members = [];
            loadApplicationMembers();
        }
    }, [state.selectedApplication]);

    const updateStatus = async () => {
        let res = await graphqlFetch({
            query: UpdateApplication,
            variables: {
                aiUuid: state.selectedApplication.aiUuid,
                aiStat: !state.selectedApplication.aiStat,
            },
        });
        if (res) {
            message.success("成功更新应用信息");
            loadLocalApplications();
        }
    };

    const renderOperate = (_, r) => {
        return <Space split={<Divider type="vertical" />} size={4}></Space>;
    };

    const cardBodyHeight = windowInnerHeight - 90 - 20 - 54;

    return (
        <div style={{ padding: 10 }}>
            <Row gutter={10}>
                <Col span={5}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 15 }}>应用列表</span>}
                        headerExtraContent={
                            <Button icon={<IconRefresh />} onClick={() => loadLocalApplications()}>
                                刷新
                            </Button>
                        }
                        headerStyle={{ padding: "10px 14px" }}
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 1, height: cardBodyHeight, overflow: "auto" }}
                    >
                        <List
                            loading={state.loading}
                            dataSource={state.localApplications}
                            renderItem={(item) => (
                                <List.Item
                                    className={`list-item ${state.selectedApplication?.aiUuid === item.aiUuid ? "list-item-selected" : ""}`}
                                    onClick={() => (state.selectedApplication = item)}
                                >
                                    <Badge dot status={item.aiStat ? "success" : "error"}>
                                        {item.aiName}
                                    </Badge>
                                </List.Item>
                            )}
                        />
                    </SemiCard>
                </Col>
                <Col span={19}>
                    <SemiCard
                        title={<span style={{ lineHeight: "32px", fontSize: 15 }}>应用信息 - {state.selectedApplication?.aiName}</span>}
                        headerExtraContent={
                            <ButtonGroup>
                                {state.selectedApplication?.aiUuid && (
                                    <Popconfirm title="确认要改变应用的可用状态吗？" onConfirm={updateStatus}>
                                        {state.selectedApplication?.aiStat ? <Button type="danger">禁用</Button> : <Button>启用</Button>}
                                    </Popconfirm>
                                )}
                            </ButtonGroup>
                        }
                        headerStyle={{ padding: "10px 14px" }}
                        shadows="always"
                        bordered={false}
                        bodyStyle={{ padding: 10, height: cardBodyHeight, overflow: "auto" }}
                    >
                        <Card title="已授权的成员名单" size="small" style={{ marginBottom: 10 }}>
                            <List
                                loading={state.loadingMembers}
                                dataSource={state.members}
                                grid={{ gutter: 16, xs: 3, sm: 4, md: 6, lg: 6, xl: 6, xxl: 6 }}
                                renderItem={(item) => (
                                    <List.Item>
                                        {item.omName} ({item.omIfim ? "内部" : "外部"})
                                    </List.Item>
                                )}
                            />
                        </Card>

                        <Table
                            loading={state.infoLoading}
                            title={() => <div style={{ fontWeight: 600 }}>应用的客户端信息</div>}
                            bordered
                            pagination={false}
                            size="small"
                            dataSource={state.clients}
                            rowKey="atType"
                        >
                            <Column title="序号" align="center" width={60} render={(_, r, i) => i + 1} />
                            <Column title="客户端类型" dataIndex="atType" align="left" />
                            <Column title="代码大小" dataIndex="atSize" align="center" width={100} render={(_) => helper.byteConvert(_)} />
                            <Column title="发版时间" dataIndex="atPbti" align="center" width={160} render={(_) => UTCTimeToLocal(_)} />
                            <Column title="版本号" dataIndex="atVeno" align="center" width={120} />
                            <Column title="操作" dataIndex="atDesc" align="center" width={120} render={renderOperate} />
                        </Table>
                    </SemiCard>
                </Col>
            </Row>
        </div>
    );
};

export default LocalApplications;
